<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
    <% String path=request.getContextPath(); String basePath=request.getScheme() + "://" + request.getServerName() + ":"
        + request.getServerPort() + path + "/" ; %>

        <!DOCTYPE html>
        <html>

        <head>
            <base href="<%=basePath%>">

            <title></title>

            <meta http-equiv="pragma" content="no-cache">
            <meta http-equiv="cache-control" content="no-cache">
            <meta http-equiv="expires" content="0">
            <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
            <meta http-equiv="description" content="This is my page">
            <!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

        </head>

        <body>
            <%@ include file="/WEB-INF/jsp/common/headerSupply.jsp" %>
                <%@ include file="/WEB-INF/jsp/common/loadDiv.jsp" %>

                    <script type="text/javascript">
                        $(function () {
                            // $('#startTime').datebox('setValue', getBeforeCurrentDate30Days());
                            // $('#endTime').datebox('setValue', getNowFormatDate());
                            bindgrid();

                            /* $("#uploadbtn").bind("click", function (e) {
                                 $("#uploadpicker").click();
                             });*/
                        });
                    </script>

                    <style scoped="scoped">
                        .textbox {
                            height: 20px;
                            margin: 0;
                            padding: 0 2px;
                            box-sizing: content-box;
                        }

                        /*.table tr {
height: 15px;
}*/
                    </style>
                    <div class="query_criteria" id="query_criteria">
                        <div style="margin: 5px 0px">
                            <label style="margin-left: 20px; font-size: 12px;">状态：</label>
                            <input class="easyui-combobox" id="supplyAuditStatus" name="supplyAuditStatus"
                                style="width: 80px;" data-options="valueField: 'value',editable:false,
						textField: 'label',panelHeight:'auto',data: [{
							label: '待审核',
							value: '0',
							selected:true
						},{
							label: '已审核',
							value: '1'
						}]">
                            </select> <a id="search" style="margin-left: 30px" href="javascript:void(0)"
                                class="easyui-linkbutton" data-options="iconCls:'icon-search'"
                                onclick="selectList()">查询</a> <a id="export" href="javascript:void(0)"
                                class="easyui-linkbutton" data-options="iconCls:'icon-export'"
                                onclick="exportList()">导出</a>
                        </div>

                        <table id="dg"></table>

                        <div id="add" class="easyui-window" closed="true" modal="true" title="标签打印申请"
                            style="width: 900px; height: 430px; padding: 10px 20px;top:50px">
                            <form id="fm" class="ssec-form">
                                <div id="tabs" class="easyui-tabs" style="width: 855px; height: 350px">
                                    <div title="基本信息" style="padding: 5px;">
                                        <table class="table">
                                            <tr>
                                                <%-- 申请id --%>
                                                    <input id="labId" type="hidden" name="labId" />
                                                    <td>
                                                        <div class="ssec-label">客户名称：</div>
                                                    </td>
                                                    <td>
                                                        <div class="ssec-text normal">
                                                            <input id="clientName" name="clientName"
                                                                class="easyui-textbox"
                                                                data-options="required:false,disabled:true" />
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="ssec-label">客户编码：</div>
                                                    </td>
                                                    <td>
                                                        <div class="ssec-text normal">
                                                            <input id="clientCode" name="clientCode"
                                                                class="easyui-textbox"
                                                                data-options="required:false,disabled:true" />
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="ssec-label">业务员名称：</div>
                                                    </td>
                                                    <td>
                                                        <%--业务员账号--%>
                                                            <input id="salesCode" name="salesCode" type="hidden" />
                                                            <div class="ssec-text normal">
                                                                <input id="salesName" name="salesName"
                                                                    class="easyui-combogrid" data-options="required:false,disabled:true,
                                           panelWidth: 200,

			idField: 'userid',
			textField: 'username',
			url: 'sale/lables/info/getSalesList',
			method: 'post',
			delay: 500,
            mode: 'remote',
			columns: [[
				{field:'userid',hidden:true,title:'id',width:80},
				{field:'username',title:'业务员',width:120},

			]],
			fitColumns: true
		" />
                                                            </div>
                                                    </td>
                                            </tr>
                                            <tr>
                                                <td>
                                                    <div class="ssec-label">要求完成时间：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="planCompleteTime" name="planCompleteTime"
                                                            class="easyui-datebox"
                                                            data-options="required:false,disabled:true,showSeconds:false,formatter:myformatter,parser:myparser" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">数量：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="quantity" name="quantity" class="easyui-numberbox"
                                                            data-options="required:false,disabled:true" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">申请人：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="createName" name="createName" class="easyui-textbox"
                                                            data-options="required:false,disabled:true" />
                                                    </div>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>
                                                    <div class="ssec-label">申请时间：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="createTime" name="createTime" class="easyui-textbox"
                                                            data-options="disabled:true,required:false" />
                                                    </div>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>
                                                    <div class="ssec-label">供应商名称：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="supplyAuditName" name="supplyAuditName"
                                                            class="easyui-textbox"
                                                            data-options="disabled:true,required:false" />
                                                    </div>
                                                </td>

                                                <td>
                                                    <div class="ssec-label">供应商编码：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="supplyAuditId" name="supplyAuditId"
                                                            class="easyui-textbox"
                                                            data-options="disabled:true,required:false" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">确认时间：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="supplyAuditTime" name="supplyAuditTime"
                                                            class="easyui-textbox"
                                                            data-options="disabled:true,required:false" />
                                                    </div>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>
                                                    <div class="ssec-label">制作要求：</div>
                                                </td>
                                                <td colspan="5">
                                                    <div class="ssec-text normal">
                                                        <input id="makeRequire" style="width: 700px;height: 100px"
                                                            name="makeRequire" class="easyui-textbox"
                                                            data-options="required:false,readonly:true,multiline:true" />
                                                    </div>

                                                </td>
                                            </tr>
                                        </table>
                                    </div>
                                    <div title="附件" style="padding: 5px;">
                                        <table>
                                            <%-- <tr>
                                                <td colspan="3"><input type="button" id="uploadbtn" value="选择文件..." />
                                                    <input type="file" id="uploadpicker" accept=""
                                                        onchange="changeFile()" multiple style="display: none;" />
                                                    <span>（文件名称不能包含斜杠、空格、&等特殊字符）</span>
                                                </td>
                                                </tr>--%>
                                                <tr>
                                                    <td><label style="width: 40%; text-align: right;">附件下载：</label>
                                                        <ul id="checkfileList"></ul>
                                                    </td>
                                                </tr>
                                        </table>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
        </body>
        <script>
            function audit(action) {

                let model = {
                    labId: $('#labId').val(),
                    supplyAuditStatus: action,
                    checkStatus: '0'
                };
                $.ajax({
                    type: "post",
                    dataType: "json",
                    url: 'sale/lables/info/supplyAudit',
                    data: JSON.stringify(model),
                    contentType: "application/json",
                    success: function (data) {
                        if (data.code != 60200) {
                            $.messager.alert('消息', data.msg);
                            selectList();
                        } else {
                            $.messager.alert('消息', data.msg);
                            selectList();
                            $('#add').window('close');
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                })
            }


            /**
             * 保存附件
             */
            function saveAttch(rowId, obj, action) {
                obj.labId = rowId
                let saveNum = 0
                if (selectedFileList.length > 0) {
                    $.each(selectedFileList, function (index, item) {
                        showFilediv();
                        var dataform = new FormData();
                        dataform.append("file", item);
                        var xmlhttp = null;
                        if (window.XMLHttpRequest) {// code for all new browsers
                            xmlhttp = new XMLHttpRequest();
                        } else if (window.ActiveXObject) {// code for IE5 and IE6
                            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                        }
                        if (xmlhttp != null) {
                            xmlhttp.open("POST", "api/file/springUpload?fileRow=" + rowId
                                + "&fileTable=sale_lables_info&fileName="
                                + item.name, true);
                            xmlhttp.setRequestHeader('token', localStorage.getItem('token'));
                            xmlhttp.setRequestHeader('userType', localStorage.getItem('userType'));
                            xmlhttp.send(dataform);
                            xmlhttp.onreadystatechange = callbackMethods;
                        } else {
                            alert("你的浏览器版本不兼容，请使用更高版本的浏览器");
                        }

                        function callbackMethods() {
                            if (xmlhttp.readyState == 4) {
                                if (xmlhttp.status == 200) {
                                    saveNum += 1
                                }
                                if (saveNum == selectedFileList.length) {
                                    hideFilediv();
                                    if ('submit' == action) {
                                        commit(obj)
                                    }
                                }
                            } else {
                                if (xmlhttp.status == 500) {
                                }
                            }
                        }
                    });
                } else {
                    if ('submit' == action) {
                        commit(obj)
                    }
                }
            }

            function editrow(row) {
                //编辑
                // var row = $('#dg').datagrid('getSelected');
                if (row) {
                    // 取得附件列表
                    getFileList(row)
                    $('#fm').form('load', row);
                    $('#salesName').combogrid('setValue', row.salesCode);
                    initBtn(row.supplyAuditStatus);
                    $('#add').window('open');
                    $('#tabs').tabs('select', 0);
                } else {
                    $.messager.alert('消息', '请选中一条数据');
                }
            }
        </script>
        <script>

            function initBtn(status) {
                if (status == '0') {
                    $('#tabs').tabs({
                        tools: [{
                            text: '确认',
                            iconCls: 'icon-ok',
                            handler: function () {
                                $.messager.confirm('提示', '是否确认?',
                                    function (r) {
                                        if (r) {
                                            audit('1');
                                        }
                                    });
                            }
                        }]
                    })
                } else {
                    $('#tabs').tabs({
                        tools: null
                    })
                }
            }

            /**
             *  按条件查询列表
             */
            function selectList() {
                /*var startTime = $('#startTime').datebox('getValue')
                var endTime = $('#endTime').datebox('getValue')*/
                var status = $('#supplyAuditStatus').combobox('getValue');
                var dg = $('#dg');
                dg.datagrid('enableFilter');
                dg.datagrid('load', {
                    supplyAuditStatus: status ? status : ''
                });
            }

            function bindgrid() {
                /* var startTime = $('#startTime').datebox('getValue')
                 var endTime = $('#endTime').datebox('getValue')*/
                var status = $('#supplyAuditStatus').combobox('getValue');
                $('#dg').datagrid({
                    title: '标签打印列表',
                    queryParams: {
                        supplyAuditStatus: status
                    },
                    url: "sale/lables/info/selectList",
                    iconCls: 'icon-application',
                    width: getWidth(0.98),
                    height: 415,
                    nowrap: true,
                    filterDelay: 0,
                    rownumbers: true,
                    animate: false,
                    collapsible: false,
                    clientPaging: false,
                    remoteFilter: true,
                    singleSelect: true,
                    pagination: true,
                    remoteSort: true,
                    frozenColumns: [[]],
                    columns: [
                        [
                            {
                                field: 'labId',
                                title: '标签申请ID',
                                sortable: true,
                                hidden: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'clientName',
                                title: '客户名称',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'clientCode',
                                title: '客户编码',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'salesName',
                                title: '业务员名称',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'salesCode',
                                title: '业务员账号',
                                sortable: true,
                                hidden: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'salesDeptId',
                                title: '所属部门id',
                                sortable: true,
                                hidden: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'planCompleteTime',
                                title: '要求完成时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'quantity',
                                title: '数量',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'makeRequire',
                                title: '制作要求',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'createTime',
                                title: '申请时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'createName',
                                title: '申请人',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'auditTime',
                                title: '审核时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            },
                            {
                                field: 'supplyAuditName',
                                title: '供应商确认人',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            },
                            {
                                field: 'supplyAuditTime',
                                title: '确认时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'checkName',
                                title: '核对人名称',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            },
                            {
                                field: 'checkStatus',
                                title: '是否核对',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val == '1' ? '已核对' : '待核对';
                                }
                            }, {
                                field: 'checkId',
                                title: '核对人id',
                                sortable: true,
                                hidden: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'checkTime',
                                title: '核对确认时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }]],
                    toolbar: [
                        {
                            text: '确认',
                            iconCls: 'icon-edit',
                            handler: function () {
                                //编辑
                                let row = $('#dg').datagrid('getSelected');
                                if (row) {
                                    editrow(row)
                                } else {
                                    $.messager.alert('消息', '请选中一条数据');
                                }
                            }
                        }],
                    onLoadSuccess: function () {
                    },
                    onDblClickRow: function () {
                    }
                });
                $('#dg').datagrid('enableFilter');
            }


            // 导出为Excel
            function exportList() {

                let status = $('#supplyAuditStatus').combobox('getValue')
                var form = [];
                /* form.push('startTime=' + (startTime ? startTime : ''));
                 form.push('endTime=' + (endTime ? endTime : ''));*/
                form.push('supplyAuditStatus=' + (status ? status : ''));
                let url = "sale / lables / info/export"
                let xhr = new XMLHttpRequest()
                xhr.open('POST', url, true)
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.setRequestHeader('token', localStorage.getItem('token'));
                xhr.setRequestHeader('userType', localStorage.getItem('userType'));
                xhr.responseType = 'blob'
                xhr.onload = function () {
                    if (this.status == 200) {
                        let blob = this.response
                        let reader = new FileReader()
                        reader.readAsDataURL(blob)
                        reader.onload = function (e) {
                            let a = document.createElement('a')
                            a.download = '' + new Date().toLocaleDateString() + '-' + new Date().toLocaleTimeString() + '.xlsx'
                            a.href = e.target.result
                            $('body').append(a)
                            a.click()
                            $(a).remove()
                        }
                    }
                }
                xhr.send(form.join('&'))
            }
        </script>
        <%-- 文件操作 --%>
            <script type="text/javascript">
                var selectedFileList = [];//已选文件列表
                var succsessCount = 0;//上传成功文件个数
                var errorCount = 0;//上传失败文件个数
                /************文件处理部分*************/


                /**
                 *文件框改变事件
                 */
                function changeFile() {
                    var files = $("#uploadpicker").prop("files");
                    $
                        .each(
                            files,
                            function (index, item) {
                                let choiseFile = $("#checkfileList>li");
                                if (choiseFile.length > 0) {//文件去重
                                    let count = 0;
                                    $.each(choiseFile, function (index1, item1) {
                                        if (item.name == item1.innerText) {
                                            count++;
                                        }
                                    });
                                    if (count == 0) {
                                        if (checkFileLength(item.size)) {
                                            if (item.name.includes('&') || item.name.includes('\\') || item.name.includes(' ')) {
                                                alert('文件名不能包含&、斜杠、反斜杠、空格等特殊字符！');
                                                return;
                                            }
                                            $("#checkfileList")
                                                .append(
                                                    "<li class=\"fileinfo\">"
                                                    + item.name
                                                    + "<a style=\"display: none; color: red; margin-left: 10px;\" href=\"javascript:void(0)\" onclick=\"RemoveFile(this,'"
                                                    + item.name
                                                    + "')\">删除</a>"
                                                    + "</li>");
                                            selectedFileList.push(item);
                                            AddMoushover();
                                        }
                                    }
                                } else {
                                    if (checkFileLength(item.size)) {
                                        if (item.name.includes('&') || item.name.includes('\\') || item.name.includes(' ')) {
                                            alert('文件名不能包含&、斜杠、反斜杠、空格等特殊字符！');
                                            return;
                                        }
                                        $("#checkfileList")
                                            .append(
                                                "<li class=\"fileinfo\">"
                                                + item.name
                                                + "<a style=\"display: none; color: red; margin-left: 10px;\" href=\"javascript:void(0)\" onclick=\"RemoveFile(this,'"
                                                + item.name
                                                + "')\">删除</a>"
                                                + "</li>");
                                        selectedFileList.push(item);
                                        AddMoushover();
                                    }
                                }
                            });
                }

                /**
                 *    判断文件是否超过限制大小
                 * @param fileLen
                 * @returns {boolean}
                 */
                function checkFileLength(fileLen) {
                    if (fileLen > 102400000) {
                        $.messager.alert("提示", "上传文件大小不能超过100M", "error");
                        return false;
                    }
                    return true;
                }

                /**
                 * //添加鼠标经过事件，鼠标划过时显示“删除”
                 * @constructor
                 */
                function AddMoushover() {
                    $(".fileinfo").hover(function () {
                        $(this).find("a").last().css("display", "");
                    }, function () {
                        $(this).find("a").last().css("display", "none");
                    });
                }

                /**
                 *  移除已选择的文件
                 */

                function RemoveFile(obj, fileId) {
                    $.messager.confirm("提示", "确认删除当前文件?", function (e) {
                        if (e) {
                            let index = $("#checkfileList>li").index($(obj).parent());
                            selectedFileList.splice(index, 1);
                            $(obj).parent().remove();

                            $.ajax({
                                type: "post",
                                url: 'file/deleteFile?fileId=' + fileId,
                                success: function (data) {
                                    $.messager.alert('消息', data);
                                },
                                error: function (XMLHttpRequest, textStatus,
                                    errorThrown) {
                                    $.messager.alert('消息', errorThrown);
                                }
                            });

                        }
                    });
                }

                /**
                 * 取得该条数据所属的文件列表
                 * @param row
                 */
                function getFileList(row) {
                    $.ajax({
                        type: "post",
                        url: "file/getFileList",
                        data: {
                            fileTable: "sale_lables_info",
                            fileRow: row.labId
                        },
                        success: function (data) {
                            const dataArray = eval(data);
                            initFile(dataArray, row.status);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            $.messager.alert('消息', errorThrown);
                        }
                    });
                }

                /**
                 * 初始化该条数据的文件列表
                 * @param dataArray
                 */
                function initFile(dataArray, status) {
                    $("#checkfileList").empty();
                    // 			sselectedFileNameList = [];
                    selectedFileList = [];
                    dataArray
                        .forEach(function (e, i, a) {
                            $("#checkfileList")
                                .append(
                                    "<li class=\"fileinfo\">"
                                    + "<a style=\" color: blue; margin-left: 30px;\" href=\"javascript:void(0)\" onclick=\"downloadFile('"
                                    + e.FILE_NAME
                                    + "','"
                                    + e.FILE_ID
                                    + "')\">"
                                    + e.FILE_NAME
                                    + "</a>"
                                    + (status > 0 ? '' : "</a>"
                                        + "<a style=\"display: none; color: red; margin-left: 30px;\" href=\"javascript:void(0)\" onclick=\"RemoveFile(this,'"
                                        + e.FILE_ID + "')\">删除</a>")
                                    + "</li>");
                            if (status > 0) {
                            } else {
                                AddMoushover();
                            }
                        });
                }

                // 文件下载
                function downloadFile(fileName, fileRow) {
                    let url = 'api/file/download?id=' + fileRow
                    let xhr = new XMLHttpRequest()
                    xhr.open('GET', url, true)
                    xhr.setRequestHeader('token', localStorage.getItem('tokenSupply'));
                    xhr.setRequestHeader('userType', localStorage.getItem('userType'));
                    xhr.responseType = 'blob'
                    xhr.onload = function (data) {
                        if (this.status == 200) {
                            let blob = this.response
                            let reader = new FileReader()
                            reader.readAsDataURL(blob)
                            reader.onload = function (e) {
                                let a = document.createElement('a')
                                a.download = fileName
                                a.href = e.target.result
                                $('body').append(a)
                                a.click()
                                $(a).remove()
                            }
                        } else {

                        }
                    }
                    xhr.send()
                }
            </script>

        </html>